<template>
	<div class="addPurchase">
		<el-button type="primary" plain @click="toBack">返回</el-button>
		<h3>订单详情</h3>
		<el-form inline label-position="top" :model="purchase" :rules="rules" ref="ruleForm">
			<el-form-item label="订单编号" v-if="purchase.id !== null" style="width: 350px;">
				<el-input v-model="purchase.id" placeholder="订单编号" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="供应商" prop="suppliersId" style="width: 350px;">
				<el-input :value="selectSuppliers.suppliersName" placeholder="选择供应商" readonly :disabled="readonly"
					@focus="purchaseDialogShow">
				</el-input>
			</el-form-item>
			<el-form-item label="采购人" prop="userId" style="width: 350px;" 
				v-if="userInfo.roleId === 1 || userInfo.roleId === 4" key="userId">
				<el-select v-model="purchase.userId" filterable remote placeholder="按名字搜索" @change="selectUserChange"
					:remote-method="getUserList" :loading="userLoading" :disabled="readonly"
					@focus="getUserList('')" style="width: 100%;">
					<el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="结款方式" style="width: 350px;">
				<el-select v-model="purchase.paymentMethod" :disabled="readonly" style="width: 100%;">
					<el-option label="现金" :value="0"></el-option>
					<el-option label="月结" :value="1"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="总金额" style="width: 350px;">
				<el-input v-model="purchase.price" type="number" placeholder="总金额" step="0.01"
					@input="checkPrice" :readonly="readonly">
				</el-input>
			</el-form-item>
			<el-form-item label="备注" style="width: 350px;">
				<el-input v-model="purchase.remark" placeholder="备注" :readonly="readonly">
				</el-input>
			</el-form-item>
			<el-form-item label="零件列表" style="width: 100%;">
				<el-button v-if="!readonly" type="text" @click="devicesDialogShow" >
					添加零件
				</el-button>
				<div>
					<el-table :data="purchase.parts" border stripe style="width: 100%" :max-height="500">
						<el-table-column prop="i" fixed="left" label="序号" width="60">
						</el-table-column>
						<el-table-column label="图片" width="120">
							<template slot-scope="scope">
								<el-image :src="READ_IMG_URL+scope.row.image" style="width: 90px; height: 90px;"
									:preview-src-list="new Array(READ_IMG_URL+scope.row.image)">
								</el-image>
							</template>
						</el-table-column>
						<el-table-column prop="partName" label="零件名称" fit>
						</el-table-column>
						<el-table-column prop="model" label="零件型号" fit>
						</el-table-column>
						<el-table-column label="采购单价" width="120">
							<template slot-scope="scope">
								<el-input v-model="scope.row.purchasePrice"
									type="number" step="0.01" :readonly="readonly"
									@change="changeUnitPrice($event,scope.row)">
								</el-input>
<!-- 								<el-input v-model="scope.row.purchasePrice" 
									type="number" step="0.01" :readonly="readonly"
									@input="checkUnitPrice($event,scope.row)" 
									@change="changeUnitPrice($event,scope.row)">
								</el-input> -->
							</template>
						</el-table-column>
						<el-table-column label="运输费" width="120">
							<template slot-scope="scope">
								<el-input v-model="scope.row.freight"
									type="number" step="0.01" :readonly="readonly"
									@change="changeUnitPrice($event,scope.row)">
								</el-input>
<!-- 								<el-input v-model="scope.row.freight" 
									type="number" step="0.01" :readonly="readonly"
									@input="checkUnitFreight($event,scope.row)" 
									@change="changeUnitPrice($event,scope.row)">
								</el-input> -->
							</template>
						</el-table-column>
						<el-table-column prop="isIncludeTax" label="是否含税" width="120">
							<template slot-scope="scope">
								<el-select v-model="scope.row.isIncludeTax" :disabled="readonly">
									<el-option label="含税" :value="0"></el-option>
									<el-option label="不含税" :value="1"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="partCount" label="采购数量" width="120">
							<template slot-scope="scope">
								<el-input v-model="scope.row.partCount" type="number"
									placeholder="采购数量" :readonly="readonly"
									@change="changeUnitPrice($event,scope.row)">
								</el-input>
<!-- 								<el-input v-model="scope.row.partCount" type="number"
									placeholder="采购数量" :readonly="readonly"
									@input="checkPartCount($event,scope.row)"
									@change="changeUnitPrice($event,scope.row)">
								</el-input> -->
							</template>
						</el-table-column>
						<el-table-column label="总计" width="120">
							<template slot-scope="scope">
								<el-input v-model="scope.row.totalPrice"
									type="number" step="0.01"
									placeholder="总计" :readonly="readonly"
									@change="changeTotalPrice($event,scope.row)">
								</el-input>
<!-- 								<el-input v-model="scope.row.totalPrice" 
									type="number" step="0.01"
									placeholder="总计" readonly
									@input="checkTotalPrice($event,scope.row)"
									@change="changeTotalPrice($event,scope.row)">
								</el-input> -->
							</template>
						</el-table-column>
						<el-table-column label="操作" width="70" v-if="!readonly">
							<template slot-scope="scope">
								<el-button type="text" @click="deleteParts(scope.row)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</el-form-item>
			<el-form-item v-if="!readonly">
				<el-button @click="reset">重置</el-button>
				<el-button type="primary" @click="onSubmit" v-debounce>提交</el-button>
			</el-form-item>
		</el-form>
		<!-- 选择供应商弹窗 -->
		<el-dialog style="margin-top:0" :visible.sync="suppliersShow" width="75%" title="选择供应商">
			<div style=" width: 100%;display: flex;justify-content: space-between;">
				<!-- 条件查询 -->
				<div style="display: flex;">
					<el-input v-model="suppliers.suppliersName" clearable 
						@change="getSupplierList()"
						style="width: 250px;margin-right: 10px;" placeholder="按名称,电话,地址搜索">
					</el-input>
				</div>
			</div>
			<div class="data-table">
				<el-table :data="suppliersList" v-loading="suppliersLoading" border stripe 
					style="width: 100%" :max-height="430">
					<el-table-column prop="i" label="序号" width="60"></el-table-column>
					<el-table-column prop="suppliersName" label="供应商名称" width="200">
					</el-table-column>
					<el-table-column prop="suppliersPhone" label="联系电话" width="150">
					</el-table-column>
					<el-table-column prop="address" label="联系地址" fit></el-table-column>
					<el-table-column prop="remark" label="备注" width="200"></el-table-column>
					<el-table-column label="操作" width="100" fixed="right">
						<template slot-scope="scope">
							<el-button type="text" @click="selectSupplier(scope.row)">
								选择
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination background @size-change="suppliersSizeChange" @current-change="suppliersCurrentChange"
					:current-page="suppliers.currentPage" :page-sizes="[20, 50, 100]" :page-size="suppliers.pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="suppliers.total">
				</el-pagination>
			</div>
		</el-dialog>
		<!-- 选择零件弹窗 -->
		<el-dialog style="margin-top:0" :visible.sync="devicesShow" width="80%" title="选择零件">
			<div style=" width: 100%;display: flex;justify-content: space-between;margin-bottom: 10px;">
				<div>
					<el-button type="primary" @click="confirmParts">确定</el-button>
				</div>
				<!-- 条件查询 -->
				<div>
					<el-input v-model="devices.partName" placeholder="按名称型号搜索" clearable @change="getDevicesList">
					</el-input>
				</div>
			</div>
			<div class="data-table">
				<el-table :data="devicesList" v-loading="devicesLoading" border 
					style="width: 100%" :max-height="430" :row-key="(row) => row.id"
					@selection-change="handleSelectionChange" ref="multipleTable">
					<el-table-column type="selection" :reserve-selection="true" width="40">
					</el-table-column>
					<el-table-column prop="i" label="序号" width="80">
					</el-table-column>
					<el-table-column label="产品图片" width="125">
						<template slot-scope="item">
							<el-image style="width: 100px; height: 100px" 
								:src="READ_IMG_URL+item.row.image"
								:preview-src-list="new Array(READ_IMG_URL+item.row.image)">
							</el-image>
						</template>
					</el-table-column>
					<el-table-column prop="partName" label="零件名称" fit>
					</el-table-column>
					<el-table-column prop="model" label="零件型号" fit>
					</el-table-column>
					<el-table-column prop="devicesDescribe" label="产品描述" fit>
					</el-table-column>
					<el-table-column prop="remark" label="备注" fit>
					</el-table-column>
					<el-table-column prop="cost" label="采购单价" fit>
					</el-table-column>
					<el-table-column prop="count" label="库存数量" fit>
					</el-table-column>
				</el-table>
				<el-pagination background @size-change="devicesSizeChange" @current-change="devicesCurrentChange"
					:current-page="devices.currentPage" :page-sizes="[20, 50, 100]" :page-size="devices.pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="devices.total">
				</el-pagination>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import warehouseApi from "../../../api/warehouse.js";
	import userApi from "../../../api/user.js";
  import config from '../../../api/apiURL.js';
	export default {
		data() {
			return {
        READ_IMG_URL: config.READ_IMG_URL,
				userInfo: {},
				purchase: {
					id: null,
					suppliersId: null, // 供应商
					parts: [], //零件列表
					userId: null, // 采购人
					price: 0, // 总金额
					paymentMethod: 0, //0现金，1月结
					remark: null, //备注
				},
				suppliersList: [],
				devices: {
					partName: null,
					isProduct: 1, // 零件
					currentPage: 1,
					pageSize: 50,
					total: 0
				},
				devicesList: [],
				devicesLoading: false,
				devicesShow: false,
				selectDevicesList: [],
				suppliers: {
					suppliersName: null,
					currentPage: 1,
					pageSize: 50,
					total: 0
				},
				suppliersLoading: false,
				suppliersShow: false,
				suppliersList: [],
				selectSuppliers: {},
				readonly: false,
				userLoading: false,
				userList: [],
				rules: {
					suppliersId: [{
						required: true, message: '请选择供应商', trigger: 'change'
					}],
					userId: [{
						required: true, message: '请选择采购人', trigger: 'change'
					}]
				},
			}
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
			this.userInfo.roleId = parseInt(this.userInfo.roleId);
			const id = localStorage.getItem("purchaseId");
			if (id) {
				this.purchase.id = id
				this.getPurchaseOrders();
			}
		},
		destroyed() {
			localStorage.removeItem("purchaseId");
		},
		methods: {
			// 返回上个页面
			toBack() {
				this.$router.push({
					path: "/warehouse/purchase/purchasing"
				})
			},
			// 获取采购订单
			getPurchaseOrders(){
				const loading = this.$loading({
				    lock: true,
				    text: 'Loading',
				    spinner: 'el-icon-loading',
				    background: 'rgba(0, 0, 0, 0.7)'
				});
				const data = {
					id: this.purchase.id
				}
				warehouseApi.getPurchaseOrders(data).then(res =>{
					if (res.code === 200){
						this.purchase = res.data
						this.purchase.parts = res.data.parts.map((item,index) =>{
							item.i = index + 1;
							return item;
						})
						this.getSuppliers(this.purchase.suppliersId);
						this.getUser(this.purchase.userId);
						
						if (this.purchase.orderStatus === "0"){
							this.readonly = true
						}
					}
				}).finally(() =>{
					loading.close();
				})
			},
			// 获取单个供应商
			getSuppliers(id){
				const data = {
					id: id
				}
				warehouseApi.getSuppliers(data).then(res =>{
					if (res.code === 200){
						this.selectSuppliers = res.data
					}
				})
			},
			// 供应商弹窗
			purchaseDialogShow() {
				this.getSupplierList();
				this.suppliersShow = true;
			},
			// 获取供应商列表
			getSupplierList(){
				this.suppliersLoading = true;
				warehouseApi.getSuppliersList(this.suppliers).then(res =>{
					if (res.code === 200){
						this.suppliers.total = res.data.total;
						this.suppliersList = res.data.suppliersVoList.map((item,index) =>{
							item.i = (this.suppliers.currentPage - 1)*this.suppliers.pageSize + index + 1;
							item.address = item.province + item.city + item.district + item
								.suppliersAddress
							return item;
						})
						this.suppliersLoading = false;
					}
				})
			},
			// 页码变化
			suppliersCurrentChange(curPage) {
				this.suppliers.currentPage = curPage
				this.getSupplierList()
			},
			// pageSize变化
			suppliersSizeChange(pageSize) {
				this.suppliers.pageSize = pageSize
				this.getSupplierList()
			},
			// 选择供应商
			selectSupplier(item){
				this.purchase.suppliersId = item.id
				this.selectSuppliers = item
				this.suppliersShow = false;
			},
			// 获取单个用户
			getUser(id){
				this.userList = []
				const data = {
					id: id
				}
				userApi.getUser(data).then(res =>{
					if (res.code === 200){
						this.userList.push(res.data);
					}
				})
			},
			// 获取用户列表
			getUserList(query) {
				this.userLoading = true;
				const data = {
					nickName: query,
				}
				userApi.fuzzyQuery(data).then(res => {
					if (res.code === 200) {
						this.userList = res.data.userVoList
						this.userLoading = false;
					}
				})
			},
			// 确定采购人
			selectUserChange(e) {
				if (this.purchase.id !== null) {
					const data = {
						id: this.purchase.id,
						userId: e
					}
					warehouseApi.changeUser(data).then(res => {
						if (res.code === 200) {
							this.$message.success("修改成功")
						}
					})
				} else {
					this.purchase.userId = e
				}
			},
			// 打开选择零件弹窗
			devicesDialogShow() {
				this.getDevicesList();
				this.devicesShow = true;
			},
			// 获取零件列表
			getDevicesList() {
				this.devicesLoading = true;
				this.devicesList = [];
				warehouseApi.getDeviceList(this.devices).then(res => {
					if (res.code === 200) {
						//console.log("产品列表=>", res.data)
						this.devices.total = res.data.total;
						this.devicesList = res.data.devicesList.map((item, index) => {
							item.i = (this.devices.currentPage - 1) * this.devices.pageSize + index + 1;
							return item;
						})
						// 显示已选择的
						this.$refs.multipleTable.clearSelection()
						if (this.purchase.parts.length > 0) {
							this.devicesList.forEach(row => {
								this.purchase.parts.forEach(part => {
									if (part.partId === row.id) {
										this.$refs.multipleTable.toggleRowSelection(row,true);
									}
								})
							})
						}
					}
				}).finally(() =>{
					this.devicesLoading = false;
				})
			},
			// 页码变化
			devicesCurrentChange(curPage) {
				this.devices.currentPage = curPage
				this.getDevicesList()
			},
			// pageSize变化
			devicesSizeChange(pageSize) {
				this.devices.pageSize = pageSize
				this.getDevicesList()
			},
			// 多选零件
			handleSelectionChange(e) {
				this.selectDevicesList = e;
			},
			// 确认选择
			confirmParts() {
				for (var i = 0; i < this.selectDevicesList.length; i++) {
					var devices = this.selectDevicesList[i];
					if (this.purchase.parts.length > 0){
						let flog = false;
						for (var j = 0; j < this.purchase.parts.length; j++) {
							var part = this.purchase.parts[j];
							if (part.partId === devices.id){
								flog = true;
								break;
							}
						}
						if (flog){
							continue;
						}
					}
					let data = {
						partId: devices.id,
						image: devices.image,
						partName: devices.partName,
						model: devices.model,
						purchasePrice: parseFloat(devices.cost.toString()),
            cost: parseFloat(devices.cost.toString()),
						freight: 0,
						partCount: 1,
						totalPrice: 0,
						isIncludeTax: 1,
					}
          this.changeUnitPrice(null,data);
					this.purchase.parts.push(data);
				}
				let newList = this.purchase.parts.map((item,index) => {
					item.i = index+1;
					return item;
				})
				this.purchase.parts = newList;
				this.devicesShow = false;
        this.getTotalAmount();
			},
			// 删除零件
			deleteParts(item) {
				let newList = this.purchase.parts.filter(part => part.partId !== item.partId)
				this.purchase.parts = newList.map((part,index) =>{
					part.i = index + 1;
					return part;
				})
				this.devicesList.forEach(row =>{
					if (item.partId === row.id){
						this.$refs.multipleTable.toggleRowSelection(row,false);
					}
				})
				this.getTotalAmount();
			},
			// 检查数字，小于0.00，或者超过小数点后两位返回0
			checkNumber(value) {
				if (value < 0.00) {
					value = 0;
          this.$message.error("输入的值不能为负数")
				}
				// 使用正则表达式匹配小数点后两位以内的数字或整数
				let regex = /^\d+(\.\d{1,2})?$/;
				if (!regex.test(value)) {
					value = 0
          this.$message.error("小数位不能超过小数点后两位")
				}
				return value;
			},
			// 检查输入的总金额
			checkPrice(e){
				let inputNumber = parseFloat(this.purchase.price);
				inputNumber = this.checkNumber(inputNumber);
				this.purchase.price = inputNumber
			},
			// 检查输入的单价
			checkUnitPrice(e,item){
				let inputNumber = parseFloat(item.purchasePrice);
				inputNumber = this.checkNumber(inputNumber);
				item.purchasePrice = inputNumber
			},
			// 检查输入的运费
			checkUnitFreight(e,item){
				let inputNumber = parseFloat(item.freight);
				inputNumber = this.checkNumber(inputNumber);
				item.freight = inputNumber
			},
			// 检查输入的总计
			checkTotalPrice(e,item){
				let inputNumber = parseFloat(item.totalPrice);
				inputNumber = this.checkNumber(inputNumber);
				item.totalPrice = inputNumber;
			},
			// 检查输入的数量
			checkPartCount(e,item){
				let inputNumber = parseInt(item.partCount);
				// 小于0
				if (inputNumber <= 0.00) {
					inputNumber = 1;
          this.$message.error("输入的值不能小于1")
				}
				// 使用正则表达式匹配小数点后两位以内的数字或整数
				let regex = /^\d+(\.\d{1,2})?$/;
				if (!regex.test(inputNumber)) {
					inputNumber = 1;
          this.$message.error("输入的值不能带小数")
				}
				item.partCount = inputNumber;
			},
			// 确认单价,运输费或数量，计算总计
			changeUnitPrice(e,item){
				// 检测输入的单价
				this.checkUnitPrice(e,item);
				// 检查输入的运费
				this.checkUnitFreight(e,item);
				// 检测输入的数量
				this.checkPartCount(e,item);
				// 浮点型计算处理
				let cost = parseInt(item.purchasePrice*100);
				let freight = parseInt(item.freight*100);
				let result = (cost + freight) * item.partCount;
				item.totalPrice = result / 100;
				this.getTotalAmount();
			},
			// 确认总计，计算总金额
			changeTotalPrice(e,item){
				this.checkTotalPrice(e,item);
				this.getTotalAmount();
			},
			// 计算总金额
			getTotalAmount(){
				let amount = 0.00
				this.purchase.parts.forEach(item =>{
					if (item.totalPrice){
						amount = amount + item.totalPrice
					}
				})
				this.purchase.price = amount.toFixed(2);
			},
			// 提交数据
			onSubmit(){
				this.$refs.ruleForm.validate((valid) => {
					if (!valid){
						this.$message.error("请将表单填写完整！")
						return false;
					}
					if (this.purchase.parts.length === 0) {
						this.$message.error("请选择零件！")
						return false;
					}
					if (this.purchase.id == null){
						// 新增
						warehouseApi.addPurchaseOrders(this.purchase).then(res =>{
							if (res.code === 200){
								this.$message.success("添加成功")
								this.reset();
							}
						})
					}else {
						// 修改
						warehouseApi.updatePurchaseOrders(this.purchase).then(res =>{
							if (res.code === 200){
								this.$message.success("修改成功")
								this.getPurchaseOrders();
							}
						})
					}
				});
			},
			// 重置
			reset(){
				this.$refs.ruleForm.resetFields();
				if (this.$refs.multipleTable !== null){
					this.$refs.multipleTable.clearSelection();
				}
				this.selectSuppliers = {};
				this.purchase.suppliersId = null; // 供应商
				this.purchase.parts = []; //零件列表
				this.purchase.userId = null; // 采购人
				this.purchase.price = null; // 总金额
				this.purchase.paymentMethod = null; //0现金，1月结
				this.purchase.remark = null; //备注
			}
		}
	}
</script>

<style>
	.addPurchase {}

	.data-table {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		margin-top: 10px;
	}

	.parts {
		width: 520px;
		height: 140px;
		margin-right: 20px;
		display: flex;
		background-color: #fdf6ec;
		border-radius: 10px;
	}

	.el-icon-delete:hover {
		cursor: pointer;
	}

	.el-icon-delete:active {
		color: #c70000;
	}
</style>